﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class OperationLogSettingListPage : Page, INavigableView<OperationLogSettingListViewModel>
    {
        public OperationLogSettingListViewModel ViewModel { get; }

        public OperationLogSettingListPage(OperationLogSettingListViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTreeCommand.ExecuteAsync(null);
        }

        [RelayCommand]
        private async Task Add()
        {
            await Edit(null);
        }

        [RelayCommand]
        private async Task EditById(string id)
        {
            if (!id.IsNullOrEmpty())
            {
                OperationLogSettingEditPage page = App.GetService<OperationLogSettingEditPage>();
                OperationLogSettingEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IOperationLogSettingService>.Instance.GetAsync(id);
                await page.ViewModel.InitData(id);
                page.ViewModel.IsEdit = true;
                page.ShowDialog();
                OperationLogSettingEditViewModel viewModel2 = page.ViewModel;
                if (viewModel2 != null && viewModel2.Result?.Success == true)
                {
                    await ViewModel.GetData();
                    await ViewModel.GetTreeCommand.ExecuteAsync(null);
                }
            }
        }

        [RelayCommand]
        private async Task Edit(OperationLogSettingInfo info)
        {
            OperationLogSettingEditPage page = App.GetService<OperationLogSettingEditPage>();
            if (info != null)
            {
                OperationLogSettingEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IOperationLogSettingService>.Instance.GetAsync(info.Id);
                await page.ViewModel.InitData(info.Id);
                page.ViewModel.IsEdit = true;
            }
            else
            {
                page.ViewModel.Item = new OperationLogSettingInfo
                {
                    Creator = App.ViewModel.UserInfo.FullName,
                    Editor = App.ViewModel.UserInfo.FullName
                };
                page.ViewModel.IsEdit = false;
            }
            page.ShowDialog();
           
            if (page.ViewModel.Result?.Success == true)
            {
                await ViewModel.GetData();
                await ViewModel.GetTreeCommand.ExecuteAsync(null);
            }
        }

        [RelayCommand]
        private async Task Delete(OperationLogSettingInfo info)
        {
            await ViewModel.DeleteCommand.ExecuteAsync(info);
            await ViewModel.GetData();
            await ViewModel.GetTreeCommand.ExecuteAsync(null);
        }

        [RelayCommand]
        private void Search()
        {
            ViewModel.SearchCommand.ExecuteAsync(null);
        }

        private async void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if ((sender as System.Windows.Controls.DataGrid)?.SelectedItem is OperationLogSettingInfo info)
            {
                await Edit(info);
            }
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
            {
                return;
            }
            if (selectedItems != null)
            {
                List<OperationLogSettingInfo> list = new List<OperationLogSettingInfo>();
                foreach (OperationLogSettingInfo item in selectedItems)
                {
                    list.Add(item);
                }
                ViewModel.SelectedItems = list;
            }
            else
            {
                ViewModel.SelectedItems = null;
            }
        }

        [RelayCommand]
        private void ImportExcel()
        {
            var page = App.GetService<ImportExcelPage>();
            page.ViewModel.Items?.Clear();
            page.ViewModel.TemplateFile = "记录操作日志的数据表配置-模板.xls";
            page.OnDataSave -= ExcelData_OnDataSave;
            page.OnDataSave += ExcelData_OnDataSave;
            ViewModel.Navigate(typeof(ImportExcelPage));
        }

        private string GetRowData(DataRow row, string columnName)
        {
            string result = "";
            if (row.Table.Columns.Contains(columnName))
            {
                result = row[columnName].ToString();
            }
            return result;
        }

        private async Task<bool> ExcelData_OnDataSave(DataRow dr)
        {
            DateTime dateTime = Convert.ToDateTime("1900-01-01");
            OperationLogSettingInfo operationLogSettingInfo = new OperationLogSettingInfo();
            operationLogSettingInfo.Forbid = GetRowData(dr, "是否禁用").ToInt32();
            operationLogSettingInfo.TableName = GetRowData(dr, "数据库表");
            operationLogSettingInfo.InsertLog = GetRowData(dr, "记录插入日志").ToInt32();
            operationLogSettingInfo.DeleteLog = GetRowData(dr, "记录删除日志").ToInt32();
            operationLogSettingInfo.UpdateLog = GetRowData(dr, "记录更新日志").ToInt32();
            operationLogSettingInfo.Note = GetRowData(dr, "备注");
            operationLogSettingInfo.Creator = GetRowData(dr, "创建人");
            string rowData = GetRowData(dr, "创建时间");
            if (!string.IsNullOrEmpty(rowData))
            {
                if (DateTime.TryParse(rowData, out var result) && result > dateTime)
                {
                    operationLogSettingInfo.CreateTime = result;
                }
            }
            else
            {
                operationLogSettingInfo.CreateTime = DateTime.Now;
            }
            return await BLLFactory<IOperationLogSettingService>.Instance.InsertAsync(operationLogSettingInfo);
        }

        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.TreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.TreeModel.FilteredTreeItems = ViewModel.TreeModel.TreeItems;
                return;
            }
            ViewModel.TreeModel.FilteredTreeItems = ViewModel.TreeModel.TreeItems.FindCustomNodes((CustomTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }
    }
}
